<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use DB,Validator;

class OrderController extends CommonController
{
    /**
     * Display a listing of the resource.
     * 个人中心 订单页面
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $userid = Session::get("userData")->id;
        $address =  DB::table("user_address")->where("user_id", $userid)->get();
        $data = DB::table("cart")->where("user_id", $userid)->leftJoin("goods", "cart.goods_id", "=", "goods.id")->get();
        // 加入session
        $this->putShopcarSession($userid,$data,$address);
        return view("home.order.confirm", compact("address", "data"));
//        return view('home.goods.item', compact('goodsInfo', 'goodsAttr', 'goodsAlbum'));
    }
    /*
     * 编辑默认地址
     */
    public function status($id)
    {
        $userid = Session::get("userData")->id;
        DB::table("user_address")->where("user_id", $userid)->update(["addr_status" => "0"]);
        DB::table("user_address")->where("user_id", $userid)->where("id", $id)->update(["addr_status" => "1"]);
        return redirect("/confirm");
    }
    /*
     * 修改地址
     */
    public function editConfirm(Request $request, $id)
    {
        // 获取数据
        $data = ($request->except("_token"));
//        dd($data);
        if (!$request->addr_county)
        {
            $data['addr_county'] = "";
        }
//        dd($a);
        // 验证可有可无
        // 修改数据库
        DB::table("user_address")->where("id", $id)->update($data);
        return redirect("/confirm");
    }
    /**
     * 收货地址处理
     */
    public function confirmTodo(Request $request)
    {

        $address = $request->except("_token");
        $address['user_id'] = Session::get("userData")->id;

//        dd($address);
        //有效性验证
        $this->validate($request, [
            "addr_province" => "required",
            "addr_detail" => "required",
            "addr_postcode" => "required|regex:/^\\d{6}$/",
            "addr_consignee" => "required",
            "addr_tel" => "required|regex:/^\\d{11}$/",
        ], [
            "addr_province.required" => "请选择地址",
            "addr_detail.required" => "请填写详细地址",
            "addr_postcode.required" => "请填写邮编",
            "addr_postcode.regex" => "邮编必须为6位",
            "addr_consignee.required" => "姓名必须填写",
            "addr_tel.required" => "手机号必须填写",
            "addr_tel.regex" => "手机号必须位11位",
        ]);

        // 获取到省市县的id
//        $address['addr_province'] = DB::table('area')->where('id',$address['addr_province'])->pluck('name');
//        $address['addr_city'] = DB::table('area')->where('id',$address['addr_city'])->pluck('name');
        // 执行数据创建
        $yang = DB::table("user_address")->insert($address);
        if (FALSE !== $yang ) {
            return redirect("/confirm");
        }else {
            return back()->with(["info" => "添加用户失败"]);
        }
    }
//    /*
//     * 提交订单处理 /confirm/processingTodo
//     */
//    public function processingTodo()
//    {
//        $userid = Session::get("userData")->id;
//        //查询order制定ID的数据
//        $processing =  DB::table("order")->where("user_id", $userid)->get();
//    }
    /*
     * 提交订单 /confirm/processing
     */
    public function processing()
    {
        $orderdata = array();
        $detialdata = array();
        $userid = Session::get("userData")->id;
        //查询order制定ID的数据
//        $processing =  DB::table("order")->where("user_id", $userid)->get();
        $userid = Session::get("userData")->id;
        $addr_id = 8;   // 以session获取
//        $addr_id = Session::get('orderData')->addr_id;
//        $address =  DB::table("user_address")->where("user_id", $userid)->get();
        // 获取session
        $cart = DB::table("cart")->where("user_id", $userid)->get();
//        dd($cart);

        $address = DB::table("user_address")
                ->where("user_id", $userid)
                ->where("id", $addr_id)
                ->first();
        // 生成订单编号
        $number = date("YmdHis").rand(1000, 9999);
        $ordertime = date('Y-m-d H:i:s');
        $goods = DB::table('goods');
        // 组装数据
        $orderdata['order_number'] = $number;
        $orderdata['user_id'] = $userid;
        $orderdata['order_name'] = $address->addr_consignee;
        $orderdata['order_tel'] = $address->addr_tel;
        $orderdata['order_address'] = $address->addr_province . ' ' . $address->addr_city . ' ' . $address->addr_county . ' ' . $address->addr_detail;
        $orderdata['order_code'] = $address->addr_postcode;
        $orderdata['order_time'] = $ordertime;

        $total = 0;
        foreach($cart as $k=>$c){
            // 写入数据到订单详情
            $detaildata[$k]['order_number'] = $number;
            $detaildata[$k]['goods_id'] = $c->goods_id;
            $detaildata[$k]['attr_id'] = $c->attr_id;
            $detaildata[$k]['order_goodsname'] = $goods->where('id',$c->goods_id)->pluck('goods_name');
            $detaildata[$k]['order_goodsnumber'] = $c->cart_num;
            $detaildata[$k]['order_price'] = $c->cart_price;
            $detaildata[$k]['order_totalprice'] = $c->cart_price * $c->cart_num;


            $total += $detaildata[$k]['order_totalprice'];
        }

        $orderdata['order_total'] = $total;
        // 插入到订单表
//        dd($address, $number);
        // 开启事务
        DB::beginTransaction();
        $res1 = DB::table("order")->insert($orderdata);
        $res2 = DB::table("order_details")->insert($detaildata);
        if($res1 && $res2){
            DB::commit();
            Session::put('ordernum', $number);
            // 删除购物车表数据
//            Session::forget("orderData");
//            dd($processing);
            return view('home.order.orderprocessing', compact("number", "total"));
        } else {
            DB::rollback();
            return redirect('/tips')->with(['info'=>'结算失败', 'url'=>url('/confirm')]);
        }
    }
    /*
     * 支付成功 /confirm/success
     */
    public function success()
    {
        $userid = Session::get("userData")->id;
        //查询order制定ID的数据
        $processing =  DB::table("order")->where("user_id", $userid)->get();
        $ordernum = Session::get('ordernum');
        $paytime = date('Y-m-d H:i:s');
        // 修改订单表的订单状态位已支付
        $res = DB::table('order')->where('order_number',$ordernum)->update(['order_status'=>1, 'order_paytime'=>$paytime]);
        // 修改订单详情表的订单状态
        $res2 = DB::table('order_details')->where('order_number', $ordernum)->update(['order_status'=>1]);
        return view('home.order.ordersuccess', compact("processing"));
        //goods表减去库存
    }
    
    // 获取购物车数据加入存储到session
    protected function putShopcarSession($userid,$data,$address)
    {
        $orderSession = Session::get('OrderData');
        $orderSession = $orderSession ? $orderSession : array();
        
        $orderSession[$userid]['cart'] = $data;
        
        if($address){
            foreach($address as $a){
                if($a->addr_status == 1){
                    $orderSession[$userid]['addr_id'] = $a->id;
                    break;
                }
            }
        }
        
        // 记录到session
        Session::put('OrderData', $orderSession);
    }
}